package com.itheima.travel.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.travel.domain.ResultInfo;
import com.itheima.travel.domain.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 黑马程序员
 */
@WebFilter(urlPatterns = {"/cart/*","/order/*"})
public class UserLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //1 强制类型转换（向下转型，为了使用子类的方法）
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;
        //2. 得到session,检查是否有登录的用户u
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if(user==null){
            //代表该用户没有登录,注意这里千万别重定向或者请求转发，因为我们现在项目是使用
//            vue的异步交互，如果你这里实行跳转，那么就会变成了同步，跳转也应该是要通知vue，让vue那边去提交。
            ResultInfo resultInfo = new ResultInfo(false,"未登录");
            //创建一个ObjectMapper把reusltInfo转换为json
            String json = new ObjectMapper().writeValueAsString(resultInfo);
            //通知浏览器或者vue当前写出的格式是json格式
            response.setContentType("application/json;charset=utf-8");
            //把json写出到vue上
            response.getWriter().write(json);
        }else{
            //已经登陆，直接放行
            chain.doFilter(request,response);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
